package cn.lvji.sus.redis;

import cn.lvji.sus.Config;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisStringCommands;

/**
 * redis工具类
 *
 * @author zhouzx
 */
public class RedisUtils {
    private static RedisClient redisClient;
    private static long KEEP_ALIVE = 30 * 60 * 1000;

    static {
        Long keepAlive = Config.getLongConfig("keep.alive");
        if (keepAlive != null && keepAlive > 0) {
            KEEP_ALIVE = Long.parseLong(Config.getConfig("keep.alive"));
        }
        redisClient = RedisClient.create(
                RedisURI.builder()
                        .withHost(Config.getConfig("redis.host"))
                        .withPort(Config.getIntConfig("redis.port"))
                        .withPassword(Config.getConfig("redis.password"))
                        .build());
    }


    private static StatefulRedisConnection getConnection() {
        return redisClient.connect();
    }

    public static String get(String key) {
        RedisStringCommands sync = getConnection().sync();
        return (String) sync.get(key);
    }

    public static void put(String key, String value) {
        RedisStringCommands sync = getConnection().sync();
        sync.psetex(key, KEEP_ALIVE, value);
    }
}
